home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 1.iso / toolbox / src / exampleCode / opengl / toogl / regex.c < prev    next >
C/C++ Source or Header  |  1996-11-11  |  29KB  |  1,242 lines

  1. /*
  2.  * Copyright (c) 1992, 1993 Silicon Graphics, Inc.
  3.  *
  4.  * Permission to use, copy, modify, distribute, and sell this software and
  5.  * its documentation for any purpose is hereby granted without fee, provided
  6.  * that (i) the above copyright notices and this permission notice appear in
  7.  * all copies of the software and related documentation, and (ii) the name of
  8.  * Silicon Graphics may not be used in any advertising or publicity relating 
  9.  * to the software without the specific, prior written permission of 
  10.  * Silicon Graphics.
  11.  *
  12.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF
  13.  * ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, 
  14.  * ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  15.  *
  16.  * IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, 
  17.  * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER 
  18.  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF 
  19.  * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT 
  20.  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  21.  */
  22.  
  23. /*
  24.  * regcomp and regexec -- regsub and regerror are elsewhere
  25.  *
  26.  *    Copyright (c) 1986 by University of Toronto.
  27.  *    Written by Henry Spencer.  Not derived from licensed software.
  28.  *
  29.  *    Permission is granted to anyone to use this software for any
  30.  *    purpose on any computer system, and to redistribute it freely,
  31.  *    subject to the following restrictions:
  32.  *
  33.  *    1. The author is not responsible for the consequences of use of
  34.  *        this software, no matter how awful, even if they arise
  35.  *        from defects in it.
  36.  *
  37.  *    2. The origin of this software must not be misrepresented, either
  38.  *        by explicit claim or by omission.
  39.  *
  40.  *    3. Altered versions must be plainly marked as such, and must not
  41.  *        be misrepresented as being the original software.
  42.  *
  43.  * Beware that some of this code is subtly aware of the way operator
  44.  * precedence is structured in regular expressions.  Serious changes in
  45.  * regular-expression syntax might require a total rethink.
  46.  */
  47. #include <stdio.h>
  48. #include <stdlib.h>
  49. #include "regex.h"
  50. #include "regmagic.h"
  51.  
  52. /*
  53.  * The "internal use only" fields in regexp.h are present to pass info from
  54.  * compile to execute that permits the execute phase to run lots faster on
  55.  * simple cases.  They are:
  56.  *
  57.  * regstart    char that must begin a match; '\0' if none obvious
  58.  * reganch    is the match anchored (at beginning-of-line only)?
  59.  * regmust    string (pointer into program) that match must include, or NULL
  60.  * regmlen    length of regmust string
  61.  *
  62.  * Regstart and reganch permit very fast decisions on suitable starting points
  63.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  64.  * of lines that cannot possibly match.  The regmust tests are costly enough
  65.  * that regcomp() supplies a regmust only if the r.e. contains something
  66.  * potentially expensive (at present, the only such thing detected is * or +
  67.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  68.  * supplied because the test in regexec() needs it and regcomp() is computing
  69.  * it anyway.
  70.  */
  71.  
  72. /*
  73.  * Structure for regexp "program".  This is essentially a linear encoding
  74.  * of a nondeterministic finite-state machine (aka syntax charts or
  75.  * "railroad normal form" in parsing technology).  Each node is an opcode
  76.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  77.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  78.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  79.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  80.  * opposed to a collection of them) is never concatenated with anything
  81.  * because of operator precedence.)  The operand of some types of node is
  82.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  83.  * particular, the operand of a BRANCH node is the first node of the branch.
  84.  * (NB this is *not* a tree structure:  the tail of the branch connects
  85.  * to the thing following the set of BRANCHes.)  The opcodes are:
  86.  */
  87.  
  88. /* definition    number    opnd?    meaning */
  89. #define    END    0    /* no    End of program. */
  90. #define    BOL    1    /* no    Match "" at beginning of line. */
  91. #define    EOL    2    /* no    Match "" at end of line. */
  92. #define    ANY    3    /* no    Match any one character. */
  93. #define    ANYOF    4    /* str    Match any character in this string. */
  94. #define    ANYBUT    5    /* str    Match any character not in this string. */
  95. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  96. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  97. #define    EXACTLY    8    /* str    Match this string. */
  98. #define    NOTHING    9    /* no    Match empty string. */
  99. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  100. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  101. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  102.             /*    OPEN+1 is number 1, etc. */
  103. #define    CLOSE    30    /* no    Analogous to OPEN. */
  104.  
  105. /*
  106.  * Opcode notes:
  107.  *
  108.  * BRANCH    The set of branches constituting a single choice are hooked
  109.  *        together with their "next" pointers, since precedence prevents
  110.  *        anything being concatenated to any individual branch.  The
  111.  *        "next" pointer of the last BRANCH in a choice points to the
  112.  *        thing following the whole choice.  This is also where the
  113.  *        final "next" pointer of each individual branch points; each
  114.  *        branch starts with the operand node of a BRANCH node.
  115.  *
  116.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  117.  *        exists to make loop structures possible.
  118.  *
  119.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  120.  *        BRANCH structures using BACK.  Simple cases (one character
  121.  *        per match) are implemented with STAR and PLUS for speed
  122.  *        and to minimize recursive plunges.
  123.  *
  124.  * OPEN,CLOSE    ...are numbered at compile time.
  125.  */
  126.  
  127. /*
  128.  * A node is one char of opcode followed by two chars of "next" pointer.
  129.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  130.  * value is a positive offset from the opcode of the node containing it.
  131.  * An operand, if any, simply follows the node.  (Note that much of the
  132.  * code generation knows about this implicit relationship.)
  133.  *
  134.  * Using two bytes for the "next" pointer is vast overkill for most things,
  135.  * but allows patterns to get big without disasters.
  136.  */
  137. #define    OP(p)    (*(p))
  138. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  139. #define    OPERAND(p)    ((p) + 3)
  140.  
  141. /*
  142.  * See regmagic.h for one further detail of program structure.
  143.  */
  144.  
  145.  
  146. /*
  147.  * Utility definitions.
  148.  */
  149. #ifndef CHARBITS
  150. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  151. #else
  152. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  153. #endif
  154.  
  155. #define    FAIL(m)    { regerror(m); return(NULL); }
  156. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  157. #define    META    "^$.[()|?+*\\"
  158.  
  159. /*
  160.  * Flags to be passed up and down.
  161.  */
  162. #define    HASWIDTH    01    /* Known never to match null string. */
  163. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  164. #define    SPSTART        04    /* Starts with * or +. */
  165. #define    WORST        0    /* Worst case. */
  166.  
  167. /*
  168.  * Global work variables for regcomp().
  169.  */
  170. static char *regparse;        /* Input-scan pointer. */
  171. static int regnpar;        /* () count. */
  172. static char regdummy;
  173. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  174. static long regsize;        /* Code size. */
  175.  
  176. /*
  177.  * Forward declarations for regcomp()'s friends.
  178.  */
  179. #ifndef STATIC
  180. #define    STATIC    static
  181. #endif
  182. STATIC char *reg();
  183. STATIC char *regbranch();
  184. STATIC char *regpiece();
  185. STATIC char *regatom();
  186. STATIC char *regnode();
  187. STATIC char *regnext();
  188. STATIC void regc();
  189. STATIC void reginsert();
  190. STATIC void regtail();
  191. STATIC void regoptail();
  192. #ifdef STRCSPN
  193. STATIC int strcspn();
  194. #endif
  195.  
  196. /*
  197.  - regcomp - compile a regular expression into internal code
  198.  *
  199.  * We can't allocate space until we know how big the compiled form will be,
  200.  * but we can't compile it (and thus know how big it is) until we've got a
  201.  * place to put the code.  So we cheat:  we compile it twice, once with code
  202.  * generation turned off and size counting turned on, and once "for real".
  203.  * This also means that we don't allocate space until we are sure that the
  204.  * thing really will compile successfully, and we never have to move the
  205.  * code and thus invalidate pointers into it.  (Note that it has to be in
  206.  * one piece because free() must be able to free it all.)
  207.  *
  208.  * Beware that the optimization-preparation code in here knows about some
  209.  * of the structure of the compiled regexp.
  210.  */
  211. regexp *
  212. regcomp(exp)
  213. char *exp;
  214. {
  215.     register regexp *r;
  216.     register char *scan;
  217.     register char *longest;
  218.     register int len;
  219.     int flags;
  220.  
  221.     if (exp == NULL)
  222.         FAIL("NULL argument");
  223.  
  224.     /* First pass: determine size, legality. */
  225.     regparse = exp;
  226.     regnpar = 1;
  227.     regsize = 0L;
  228.     regcode = (char *)®dummy;    /* cast shuts up a false compiler warning */
  229.     regc(MAGIC);
  230.     if (reg(0, &flags) == NULL)
  231.         return(NULL);
  232.  
  233.     /* Small enough for pointer-storage convention? */
  234.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  235.         FAIL("regexp too big");
  236.  
  237.     /* Allocate space. */
  238.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  239.     if (r == NULL)
  240.         FAIL("out of space");
  241.  
  242.     /* Second pass: emit code. */
  243.     regparse = exp;
  244.     regnpar = 1;
  245.     regcode = r->program;
  246.     regc(MAGIC);
  247.     if (reg(0, &flags) == NULL)
  248.         return(NULL);
  249.  
  250.     /* Dig out information for optimizations. */
  251.     r->regstart = '\0';    /* Worst-case defaults. */
  252.     r->reganch = 0;
  253.     r->regmust = NULL;
  254.     r->regmlen = 0;
  255.     scan = r->program+1;            /* First BRANCH. */
  256.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  257.         scan = OPERAND(scan);
  258.  
  259.         /* Starting-point info. */
  260.         if (OP(scan) == EXACTLY)
  261.             r->regstart = *OPERAND(scan);
  262.         else if (OP(scan) == BOL)
  263.             r->reganch++;
  264.  
  265.         /*
  266.          * If there's something expensive in the r.e., find the
  267.          * longest literal string that must appear and make it the
  268.          * regmust.  Resolve ties in favor of later strings, since
  269.          * the regstart check works with the beginning of the r.e.
  270.          * and avoiding duplication strengthens checking.  Not a
  271.          * strong reason, but sufficient in the absence of others.
  272.          */
  273.         if (flags&SPSTART) {
  274.             longest = NULL;
  275.             len = 0;
  276.             for (; scan != NULL; scan = regnext(scan))
  277.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  278.                     longest = OPERAND(scan);
  279.                     len = strlen(OPERAND(scan));
  280.                 }
  281.             r->regmust = longest;
  282.             r->regmlen = len;
  283.         }
  284.     }
  285.  
  286.     return(r);
  287. }
  288.  
  289. /*
  290.  - reg - regular expression, i.e. main body or parenthesized thing
  291.  *
  292.  * Caller must absorb opening parenthesis.
  293.  *
  294.  * Combining parenthesis handling with the base level of regular expression
  295.  * is a trifle forced, but the need to tie the tails of the branches to what
  296.  * follows makes it hard to avoid.
  297.  */
  298. static char *
  299. reg(paren, flagp)
  300. int paren;            /* Parenthesized? */
  301. int *flagp;
  302. {
  303.     register char *ret;
  304.     register char *br;
  305.     register char *ender;
  306.     register int parno;
  307.     int flags;
  308.  
  309.     *flagp = HASWIDTH;    /* Tentatively. */
  310.  
  311.     /* Make an OPEN node, if parenthesized. */
  312.     if (paren) {
  313.         if (regnpar >= NSUBEXP)
  314.             FAIL("too many ()");
  315.         parno = regnpar;
  316.         regnpar++;
  317.         ret = regnode(OPEN+parno);
  318.     } else
  319.         ret = NULL;
  320.  
  321.     /* Pick up the branches, linking them together. */
  322.     br = regbranch(&flags);
  323.     if (br == NULL)
  324.         return(NULL);
  325.     if (ret != NULL)
  326.         regtail(ret, br);    /* OPEN -> first. */
  327.     else
  328.         ret = br;
  329.     if (!(flags&HASWIDTH))
  330.         *flagp &= ~HASWIDTH;
  331.     *flagp |= flags&SPSTART;
  332.     while (*regparse == '|') {
  333.         regparse++;
  334.         br = regbranch(&flags);
  335.         if (br == NULL)
  336.             return(NULL);
  337.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  338.         if (!(flags&HASWIDTH))
  339.             *flagp &= ~HASWIDTH;
  340.         *flagp |= flags&SPSTART;
  341.     }
  342.  
  343.     /* Make a closing node, and hook it on the end. */
  344.     ender = regnode((paren) ? CLOSE+parno : END);    
  345.     regtail(ret, ender);
  346.  
  347.     /* Hook the tails of the branches to the closing node. */
  348.     for (br = ret; br != NULL; br = regnext(br))
  349.         regoptail(br, ender);
  350.  
  351.     /* Check for proper termination. */
  352.     if (paren && *regparse++ != ')') {
  353.         FAIL("unmatched ()");
  354.     } else if (!paren && *regparse != '\0') {
  355.         if (*regparse == ')') {
  356.             FAIL("unmatched ()");
  357.         } else
  358.             FAIL("junk on end");    /* "Can't happen". */
  359.         /* NOTREACHED */
  360.     }
  361.  
  362.     return(ret);
  363. }
  364.  
  365. /*
  366.  - regbranch - one alternative of an | operator
  367.  *
  368.  * Implements the concatenation operator.
  369.  */
  370. static char *
  371. regbranch(flagp)
  372. int *flagp;
  373. {
  374.     register char *ret;
  375.     register char *chain;
  376.     register char *latest;
  377.     int flags;
  378.  
  379.     *flagp = WORST;        /* Tentatively. */
  380.  
  381.     ret = regnode(BRANCH);
  382.     chain = NULL;
  383.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  384.         latest = regpiece(&flags);
  385.         if (latest == NULL)
  386.             return(NULL);
  387.         *flagp |= flags&HASWIDTH;
  388.         if (chain == NULL)    /* First piece. */
  389.             *flagp |= flags&SPSTART;
  390.         else
  391.             regtail(chain, latest);
  392.         chain = latest;
  393.     }
  394.     if (chain == NULL)    /* Loop ran zero times. */
  395.         (void) regnode(NOTHING);
  396.  
  397.     return(ret);
  398. }
  399.  
  400. /*
  401.  - regpiece - something followed by possible [*+?]
  402.  *
  403.  * Note that the branching code sequences used for ? and the general cases
  404.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  405.  * both the endmarker for their branch list and the body of the last branch.
  406.  * It might seem that this node could be dispensed with entirely, but the
  407.  * endmarker role is not redundant.
  408.  */
  409. static char *
  410. regpiece(flagp)
  411. int *flagp;
  412. {
  413.     register char *ret;
  414.     register char op;
  415.     register char *next;
  416.     int flags;
  417.  
  418.     ret = regatom(&flags);
  419.     if (ret == NULL)
  420.         return(NULL);
  421.  
  422.     op = *regparse;
  423.     if (!ISMULT(op)) {
  424.         *flagp = flags;
  425.         return(ret);
  426.     }
  427.  
  428.     if (!(flags&HASWIDTH) && op != '?')
  429.         FAIL("*+ operand could be empty");
  430.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  431.  
  432.     if (op == '*' && (flags&SIMPLE))
  433.         reginsert(STAR, ret);
  434.     else if (op == '*') {
  435.         /* Emit x* as (x&|), where & means "self". */
  436.         reginsert(BRANCH, ret);            /* Either x */
  437.         regoptail(ret, regnode(BACK));        /* and loop */
  438.         regoptail(ret, ret);            /* back */
  439.         regtail(ret, regnode(BRANCH));        /* or */
  440.         regtail(ret, regnode(NOTHING));        /* null. */
  441.     } else if (op == '+' && (flags&SIMPLE))
  442.         reginsert(PLUS, ret);
  443.     else if (op == '+') {
  444.         /* Emit x+ as x(&|), where & means "self". */
  445.         next = regnode(BRANCH);            /* Either */
  446.         regtail(ret, next);
  447.         regtail(regnode(BACK), ret);        /* loop back */
  448.         regtail(next, regnode(BRANCH));        /* or */
  449.         regtail(ret, regnode(NOTHING));        /* null. */
  450.     } else if (op == '?') {
  451.         /* Emit x? as (x|) */
  452.         reginsert(BRANCH, ret);            /* Either x */
  453.         regtail(ret, regnode(BRANCH));        /* or */
  454.         next = regnode(NOTHING);        /* null. */
  455.         regtail(ret, next);
  456.         regoptail(ret, next);
  457.     }
  458.     regparse++;
  459.     if (ISMULT(*regparse))
  460.         FAIL("nested *?+");
  461.  
  462.     return(ret);
  463. }
  464.  
  465. /*
  466.  - regatom - the lowest level
  467.  *
  468.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  469.  * it can turn them into a single node, which is smaller to store and
  470.  * faster to run.  Backslashed characters are exceptions, each becoming a
  471.  * separate node; the code is simpler that way and it's not worth fixing.
  472.  */
  473. static char *
  474. regatom(flagp)
  475. int *flagp;
  476. {
  477.     register char *ret;
  478.     int flags;
  479.  
  480.     *flagp = WORST;        /* Tentatively. */
  481.  
  482.     switch (*regparse++) {
  483.     case '^':
  484.         ret = regnode(BOL);
  485.         break;
  486.     case '$':
  487.         ret = regnode(EOL);
  488.         break;
  489.     case '.':
  490.         ret = regnode(ANY);
  491.         *flagp |= HASWIDTH|SIMPLE;
  492.         break;
  493.     case '[': {
  494.             register int class;
  495.             register int classend;
  496.  
  497.             if (*regparse == '^') {    /* Complement of range. */
  498.                 ret = regnode(ANYBUT);
  499.                 regparse++;
  500.             } else
  501.                 ret = regnode(ANYOF);
  502.             if (*regparse == ']' || *regparse == '-')
  503.                 regc(*regparse++);
  504.             while (*regparse != '\0' && *regparse != ']') {
  505.                 if (*regparse == '-') {
  506.                     regparse++;
  507.                     if (*regparse == ']' || *regparse == '\0')
  508.                         regc('-');
  509.                     else {
  510.                         class = UCHARAT(regparse-2)+1;
  511.                         classend = UCHARAT(regparse);
  512.                         if (class > classend+1)
  513.                             FAIL("invalid [] range");
  514.                         for (; class <= classend; class++)
  515.                             regc(class);
  516.                         regparse++;
  517.                     }
  518.                 } else
  519.                     regc(*regparse++);
  520.             }
  521.             regc('\0');
  522.             if (*regparse != ']')
  523.                 FAIL("unmatched []");
  524.             regparse++;
  525.             *flagp |= HASWIDTH|SIMPLE;
  526.         }
  527.         break;
  528.     case '(':
  529.         ret = reg(1, &flags);
  530.         if (ret == NULL)
  531.             return(NULL);
  532.         *flagp |= flags&(HASWIDTH|SPSTART);
  533.         break;
  534.     case '\0':
  535.     case '|':
  536.     case ')':
  537.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  538.         break;
  539.     case '?':
  540.     case '+':
  541.     case '*':
  542.         FAIL("?+* follows nothing");
  543.         break;
  544.     case '\\':
  545.         if (*regparse == '\0')
  546.             FAIL("trailing \\");
  547.         ret = regnode(EXACTLY);
  548.         regc(*regparse++);
  549.         regc('\0');
  550.         *flagp |= HASWIDTH|SIMPLE;
  551.         break;
  552.     default: {
  553.             register int len;
  554.             register char ender;
  555.  
  556.             regparse--;
  557.             len = strcspn(regparse, META);
  558.             if (len <= 0)
  559.                 FAIL("internal disaster");
  560.             ender = *(regparse+len);
  561.             if (len > 1 && ISMULT(ender))
  562.                 len--;        /* Back off clear of ?+* operand. */
  563.             *flagp |= HASWIDTH;
  564.             if (len == 1)
  565.                 *flagp |= SIMPLE;
  566.             ret = regnode(EXACTLY);
  567.             while (len > 0) {
  568.                 regc(*regparse++);
  569.                 len--;
  570.             }
  571.             regc('\0');
  572.         }
  573.         break;
  574.     }
  575.  
  576.     return(ret);
  577. }
  578.  
  579. /*
  580.  - regnode - emit a node
  581.  */
  582. static char *            /* Location. */
  583. regnode(op)
  584. char op;
  585. {
  586.     register char *ret;
  587.     register char *ptr;
  588.  
  589.     ret = regcode;
  590.     if (ret == ®dummy) {
  591.         regsize += 3;
  592.         return(ret);
  593.     }
  594.  
  595.     ptr = ret;
  596.     *ptr++ = op;
  597.     *ptr++ = '\0';        /* Null "next" pointer. */
  598.     *ptr++ = '\0';
  599.     regcode = ptr;
  600.  
  601.     return(ret);
  602. }
  603.  
  604. /*
  605.  - regc - emit (if appropriate) a byte of code
  606.  */
  607. static void
  608. regc(b)
  609. char b;
  610. {
  611.     if (regcode != ®dummy)
  612.         *regcode++ = b;
  613.     else
  614.         regsize++;
  615. }
  616.  
  617. /*
  618.  - reginsert - insert an operator in front of already-emitted operand
  619.  *
  620.  * Means relocating the operand.
  621.  */
  622. static void
  623. reginsert(op, opnd)
  624. char op;
  625. char *opnd;
  626. {
  627.     register char *src;
  628.     register char *dst;
  629.     register char *place;
  630.  
  631.     if (regcode == ®dummy) {
  632.         regsize += 3;
  633.         return;
  634.     }
  635.  
  636.     src = regcode;
  637.     regcode += 3;
  638.     dst = regcode;
  639.     while (src > opnd)
  640.         *--dst = *--src;
  641.  
  642.     place = opnd;        /* Op node, where operand used to be. */
  643.     *place++ = op;
  644.     *place++ = '\0';
  645.     *place++ = '\0';
  646. }
  647.  
  648. /*
  649.  - regtail - set the next-pointer at the end of a node chain
  650.  */
  651. static void
  652. regtail(p, val)
  653. char *p;
  654. char *val;
  655. {
  656.     register char *scan;
  657.     register char *temp;
  658.     register int offset;
  659.  
  660.     if (p == ®dummy)
  661.         return;
  662.  
  663.     /* Find last node. */
  664.     scan = p;
  665.     for (;;) {
  666.         temp = regnext(scan);
  667.         if (temp == NULL)
  668.             break;
  669.         scan = temp;
  670.     }
  671.  
  672.     if (OP(scan) == BACK)
  673.         offset = scan - val;
  674.     else
  675.         offset = val - scan;
  676.     *(scan+1) = (offset>>8)&0377;
  677.     *(scan+2) = offset&0377;
  678. }
  679.  
  680. /*
  681.  - regoptail - regtail on operand of first argument; nop if operandless
  682.  */
  683. static void
  684. regoptail(p, val)
  685. char *p;
  686. char *val;
  687. {
  688.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  689.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  690.         return;
  691.     regtail(OPERAND(p), val);
  692. }
  693.  
  694. /*
  695.  * regexec and friends
  696.  */
  697.  
  698. /*
  699.  * Global work variables for regexec().
  700.  */
  701. static char *reginput;        /* String-input pointer. */
  702. static char *regbol;        /* Beginning of input, for ^ check. */
  703. static char **regstartp;    /* Pointer to startp array. */
  704. static char **regendp;        /* Ditto for endp. */
  705.  
  706. /*
  707.  * Forwards.
  708.  */
  709. STATIC int regtry();
  710. STATIC int regmatch();
  711. STATIC int regrepeat();
  712.  
  713. #ifdef DEBUG
  714. int regnarrate = 0;
  715. void regdump();
  716. STATIC char *regprop();
  717. #endif
  718.  
  719. /*
  720.  - regexec - match a regexp against a string
  721.  */
  722. int
  723. regexec(prog, string)
  724. register regexp *prog;
  725. register char *string;
  726. {
  727.     register char *s;
  728.     extern char *strchr();
  729.  
  730.     /* Be paranoid... */
  731.     if (prog == NULL || string == NULL) {
  732.         regerror("NULL parameter");
  733.         return(0);
  734.     }
  735.  
  736.     /* Check validity of program. */
  737.     if (UCHARAT(prog->program) != MAGIC) {
  738.         regerror("corrupted program");
  739.         return(0);
  740.     }
  741.  
  742.     /* If there is a "must appear" string, look for it. */
  743.     if (prog->regmust != NULL) {
  744.         s = string;
  745.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  746.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  747.                 break;    /* Found it. */
  748.             s++;
  749.         }
  750.         if (s == NULL)    /* Not present. */
  751.             return(0);
  752.     }
  753.  
  754.     /* Mark beginning of line for ^ . */
  755.     regbol = string;
  756.  
  757.     /* Simplest case:  anchored match need be tried only once. */
  758.     if (prog->reganch)
  759.         return(regtry(prog, string));
  760.  
  761.     /* Messy cases:  unanchored match. */
  762.     s = string;
  763.     if (prog->regstart != '\0')
  764.         /* We know what char it must start with. */
  765.         while ((s = strchr(s, prog->regstart)) != NULL) {
  766.             if (regtry(prog, s))
  767.                 return(1);
  768.             s++;
  769.         }
  770.     else
  771.         /* We don't -- general case. */
  772.         do {
  773.             if (regtry(prog, s))
  774.                 return(1);
  775.         } while (*s++ != '\0');
  776.  
  777.     /* Failure. */
  778.     return(0);
  779. }
  780.  
  781. /*
  782.  - regtry - try match at specific point
  783.  */
  784. static int            /* 0 failure, 1 success */
  785. regtry(prog, string)
  786. regexp *prog;
  787. char *string;
  788. {
  789.     register int i;
  790.     register char **sp;
  791.     register char **ep;
  792.  
  793.     reginput = string;
  794.     regstartp = prog->startp;
  795.     regendp = prog->endp;
  796.  
  797.     sp = prog->startp;
  798.     ep = prog->endp;
  799.     for (i = NSUBEXP; i > 0; i--) {
  800.         *sp++ = NULL;
  801.         *ep++ = NULL;
  802.     }
  803.     if (regmatch(prog->program + 1)) {
  804.         prog->startp[0] = string;
  805.         prog->endp[0] = reginput;
  806.         return(1);
  807.     } else
  808.         return(0);
  809. }
  810.  
  811. /*
  812.  - regmatch - main matching routine
  813.  *
  814.  * Conceptually the strategy is simple:  check to see whether the current
  815.  * node matches, call self recursively to see whether the rest matches,
  816.  * and then act accordingly.  In practice we make some effort to avoid
  817.  * recursion, in particular by going through "ordinary" nodes (that don't
  818.  * need to know whether the rest of the match failed) by a loop instead of
  819.  * by recursion.
  820.  */
  821. static int            /* 0 failure, 1 success */
  822. regmatch(prog)
  823. char *prog;
  824. {
  825.     register char *scan;    /* Current node. */
  826.     char *next;        /* Next node. */
  827.     extern char *strchr();
  828.  
  829.     scan = prog;
  830. #ifdef DEBUG
  831.     if (scan != NULL && regnarrate)
  832.         fprintf(stderr, "%s(\n", regprop(scan));
  833. #endif
  834.     while (scan != NULL) {
  835. #ifdef DEBUG
  836.         if (regnarrate)
  837.             fprintf(stderr, "%s...\n", regprop(scan));
  838. #endif
  839.         next = regnext(scan);
  840.  
  841.         switch (OP(scan)) {
  842.         case BOL:
  843.             if (reginput != regbol)
  844.                 return(0);
  845.             break;
  846.         case EOL:
  847.             if (*reginput != '\0')
  848.                 return(0);
  849.             break;
  850.         case ANY:
  851.             if (*reginput == '\0')
  852.                 return(0);
  853.             reginput++;
  854.             break;
  855.         case EXACTLY: {
  856.                 register int len;
  857.                 register char *opnd;
  858.  
  859.                 opnd = OPERAND(scan);
  860.                 /* Inline the first character, for speed. */
  861.                 if (*opnd != *reginput)
  862.                     return(0);
  863.                 len = strlen(opnd);
  864.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  865.                     return(0);
  866.                 reginput += len;
  867.             }
  868.             break;
  869.         case ANYOF:
  870.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  871.                 return(0);
  872.             reginput++;
  873.             break;
  874.         case ANYBUT:
  875.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  876.                 return(0);
  877.             reginput++;
  878.             break;
  879.         case NOTHING:
  880.             break;
  881.         case BACK:
  882.             break;
  883.         case OPEN+1:
  884.         case OPEN+2:
  885.         case OPEN+3:
  886.         case OPEN+4:
  887.         case OPEN+5:
  888.         case OPEN+6:
  889.         case OPEN+7:
  890.         case OPEN+8:
  891.         case OPEN+9: {
  892.                 register int no;
  893.                 register char *save;
  894.  
  895.                 no = OP(scan) - OPEN;
  896.                 save = reginput;
  897.  
  898.                 if (regmatch(next)) {
  899.                     /*
  900.                      * Don't set startp if some later
  901.                      * invocation of the same parentheses
  902.                      * already has.
  903.                      */
  904.                     if (regstartp[no] == NULL)
  905.                         regstartp[no] = save;
  906.                     return(1);
  907.                 } else
  908.                     return(0);
  909.             }
  910.             break;
  911.         case CLOSE+1:
  912.         case CLOSE+2:
  913.         case CLOSE+3:
  914.         case CLOSE+4:
  915.         case CLOSE+5:
  916.         case CLOSE+6:
  917.         case CLOSE+7:
  918.         case CLOSE+8:
  919.         case CLOSE+9: {
  920.                 register int no;
  921.                 register char *save;
  922.  
  923.                 no = OP(scan) - CLOSE;
  924.                 save = reginput;
  925.  
  926.                 if (regmatch(next)) {
  927.                     /*
  928.                      * Don't set endp if some later
  929.                      * invocation of the same parentheses
  930.                      * already has.
  931.                      */
  932.                     if (regendp[no] == NULL)
  933.                         regendp[no] = save;
  934.                     return(1);
  935.                 } else
  936.                     return(0);
  937.             }
  938.             break;
  939.         case BRANCH: {
  940.                 register char *save;
  941.  
  942.                 if (OP(next) != BRANCH)        /* No choice. */
  943.                     next = OPERAND(scan);    /* Avoid recursion. */
  944.                 else {
  945.                     do {
  946.                         save = reginput;
  947.                         if (regmatch(OPERAND(scan)))
  948.                             return(1);
  949.                         reginput = save;
  950.                         scan = regnext(scan);
  951.                     } while (scan != NULL && OP(scan) == BRANCH);
  952.                     return(0);
  953.                     /* NOTREACHED */
  954.                 }
  955.             }
  956.             break;
  957.         case STAR:
  958.         case PLUS: {
  959.                 register char nextch;
  960.                 register int no;
  961.                 register char *save;
  962.                 register int min;
  963.  
  964.                 /*
  965.                  * Lookahead to avoid useless match attempts
  966.                  * when we know what character comes next.
  967.                  */
  968.                 nextch = '\0';
  969.                 if (OP(next) == EXACTLY)
  970.                     nextch = *OPERAND(next);
  971.                 min = (OP(scan) == STAR) ? 0 : 1;
  972.                 save = reginput;
  973.                 no = regrepeat(OPERAND(scan));
  974.                 while (no >= min) {
  975.                     /* If it could work, try it. */
  976.                     if (nextch == '\0' || *reginput == nextch)
  977.                         if (regmatch(next))
  978.                             return(1);
  979.                     /* Couldn't or didn't -- back up. */
  980.                     no--;
  981.                     reginput = save + no;
  982.                 }
  983.                 return(0);
  984.             }
  985.             break;
  986.         case END:
  987.             return(1);    /* Success! */
  988.             break;
  989.         default:
  990.             regerror("memory corruption");
  991.             return(0);
  992.             break;
  993.         }
  994.  
  995.         scan = next;
  996.     }
  997.  
  998.     /*
  999.      * We get here only if there's trouble -- normally "case END" is
  1000.      * the terminating point.
  1001.      */
  1002.     regerror("corrupted pointers");
  1003.     return(0);
  1004. }
  1005.  
  1006. /*
  1007.  - regrepeat - repeatedly match something simple, report how many
  1008.  */
  1009. static int
  1010. regrepeat(p)
  1011. char *p;
  1012. {
  1013.       char *strchr();
  1014.     register int count = 0;
  1015.     register char *scan;
  1016.     register char *opnd;
  1017.  
  1018.     scan = reginput;
  1019.     opnd = OPERAND(p);
  1020.     switch (OP(p)) {
  1021.     case ANY:
  1022.         count = strlen(scan);
  1023.         scan += count;
  1024.         break;
  1025.     case EXACTLY:
  1026.         while (*opnd == *scan) {
  1027.             count++;
  1028.             scan++;
  1029.         }
  1030.         break;
  1031.     case ANYOF:
  1032.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1033.             count++;
  1034.             scan++;
  1035.         }
  1036.         break;
  1037.     case ANYBUT:
  1038.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1039.             count++;
  1040.             scan++;
  1041.         }
  1042.         break;
  1043.     default:        /* Oh dear.  Called inappropriately. */
  1044.         regerror("internal foulup");
  1045.         count = 0;    /* Best compromise. */
  1046.         break;
  1047.     }
  1048.     reginput = scan;
  1049.  
  1050.     return(count);
  1051. }
  1052.  
  1053. /*
  1054.  - regnext - dig the "next" pointer out of a node
  1055.  */
  1056. static char *
  1057. regnext(p)
  1058. register char *p;
  1059. {
  1060.     register int offset;
  1061.  
  1062.     if (p == ®dummy)
  1063.         return(NULL);
  1064.  
  1065.     offset = NEXT(p);
  1066.     if (offset == 0)
  1067.         return(NULL);
  1068.  
  1069.     if (OP(p) == BACK)
  1070.         return(p-offset);
  1071.     else
  1072.         return(p+offset);
  1073. }
  1074.  
  1075. #ifdef DEBUG
  1076.  
  1077. STATIC char *regprop();
  1078.  
  1079. /*
  1080.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1081.  */
  1082. void
  1083. regdump(r)
  1084. regexp *r;
  1085. {
  1086.     register char *s;
  1087.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1088.     register char *next;
  1089.     extern char *strchr();
  1090.  
  1091.  
  1092.     s = r->program + 1;
  1093.     while (op != END) {    /* While that wasn't END last time... */
  1094.         op = OP(s);
  1095.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1096.         next = regnext(s);
  1097.         if (next == NULL)        /* Next ptr. */
  1098.             printf("(0)");
  1099.         else 
  1100.             printf("(%d)", (s-r->program)+(next-s));
  1101.         s += 3;
  1102.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1103.             /* Literal string, where present. */
  1104.             while (*s != '\0') {
  1105.                 putchar(*s);
  1106.                 s++;
  1107.             }
  1108.             s++;
  1109.         }
  1110.         putchar('\n');
  1111.     }
  1112.  
  1113.     /* Header fields of interest. */
  1114.     if (r->regstart != '\0')
  1115.         printf("start `%c' ", r->regstart);
  1116.     if (r->reganch)
  1117.         printf("anchored ");
  1118.     if (r->regmust != NULL)
  1119.         printf("must have \"%s\"", r->regmust);
  1120.     printf("\n");
  1121. }
  1122.  
  1123. /*
  1124.  - regprop - printable representation of opcode
  1125.  */
  1126. static char *
  1127. regprop(op)
  1128. char *op;
  1129. {
  1130.     register char *p;
  1131.     static char buf[50];
  1132.  
  1133.     (void) strcpy(buf, ":");
  1134.  
  1135.     switch (OP(op)) {
  1136.     case BOL:
  1137.         p = "BOL";
  1138.         break;
  1139.     case EOL:
  1140.         p = "EOL";
  1141.         break;
  1142.     case ANY:
  1143.         p = "ANY";
  1144.         break;
  1145.     case ANYOF:
  1146.         p = "ANYOF";
  1147.         break;
  1148.     case ANYBUT:
  1149.         p = "ANYBUT";
  1150.         break;
  1151.     case BRANCH:
  1152.         p = "BRANCH";
  1153.         break;
  1154.     case EXACTLY:
  1155.         p = "EXACTLY";
  1156.         break;
  1157.     case NOTHING:
  1158.         p = "NOTHING";
  1159.         break;
  1160.     case BACK:
  1161.         p = "BACK";
  1162.         break;
  1163.     case END:
  1164.         p = "END";
  1165.         break;
  1166.     case OPEN+1:
  1167.     case OPEN+2:
  1168.     case OPEN+3:
  1169.     case OPEN+4:
  1170.     case OPEN+5:
  1171.     case OPEN+6:
  1172.     case OPEN+7:
  1173.     case OPEN+8:
  1174.     case OPEN+9:
  1175.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1176.         p = NULL;
  1177.         break;
  1178.     case CLOSE+1:
  1179.     case CLOSE+2:
  1180.     case CLOSE+3:
  1181.     case CLOSE+4:
  1182.     case CLOSE+5:
  1183.     case CLOSE+6:
  1184.     case CLOSE+7:
  1185.     case CLOSE+8:
  1186.     case CLOSE+9:
  1187.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1188.         p = NULL;
  1189.         break;
  1190.     case STAR:
  1191.         p = "STAR";
  1192.         break;
  1193.     case PLUS:
  1194.         p = "PLUS";
  1195.         break;
  1196.     default:
  1197.         regerror("corrupted opcode");
  1198.         break;
  1199.     }
  1200.     if (p != NULL)
  1201.         (void) strcat(buf, p);
  1202.     return(buf);
  1203. }
  1204. #endif
  1205.  
  1206. /*
  1207.  * The following is provided for those people who do not have strcspn() in
  1208.  * their C libraries.  They should get off their butts and do something
  1209.  * about it; at least one public-domain implementation of those (highly
  1210.  * useful) string routines has been published on Usenet.
  1211.  */
  1212. #ifdef STRCSPN
  1213. /*
  1214.  * strcspn - find length of initial segment of s1 consisting entirely
  1215.  * of characters not from s2
  1216.  */
  1217.  
  1218. static int
  1219. strcspn(s1, s2)
  1220. char *s1;
  1221. char *s2;
  1222. {
  1223.     register char *scan1;
  1224.     register char *scan2;
  1225.     register int count;
  1226.  
  1227.     count = 0;
  1228.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1229.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1230.             if (*scan1 == *scan2++)
  1231.                 return(count);
  1232.         count++;
  1233.     }
  1234.     return(count);
  1235. }
  1236. #endif
  1237.  
  1238. void regerror(char *s)
  1239. {
  1240.     fprintf(stderr, "regerror: %s\n", s);
  1241. }
  1242.